package spitter.repository;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import spitter.domain.Spitter;

import java.io.Serializable;
import java.util.List;

//@Repository
public class HibernateSpitterRepository {

    private SessionFactory sessionFactory;

    @Autowired
    public HibernateSpitterRepository(SessionFactory sessionFactory){
        this.sessionFactory  =sessionFactory;
    }

    public Spitter save(Spitter spitter){
        Serializable id = currentSession().save(spitter);

        return new Spitter((Long)id,
                spitter.getFirstName(),
                spitter.getLastName(),
                spitter.getUserName(),
                spitter.getEmail(),
                spitter.getPassword());
    }

    public Spitter findByUserName(String username){
        return (Spitter) currentSession().createCriteria(Spitter.class)
                .add(Restrictions.eq("username",username))
                .list().get(0);
    }

    public Spitter findOne(Long id){
        return (Spitter) currentSession().get(Spitter.class,id);
    }


    public long count(){
        return findAll().size();
    }

    public List<Spitter> findAll(){
        return (List<Spitter>)currentSession().createCriteria(Spitter.class).list();
    }
    private Session currentSession(){
        return sessionFactory.getCurrentSession();
    }
}
